package online.hxstar.learn.serialization;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author huxing
 * @date 2018-12-15 10:55
 */
public class SubReqServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        SubscribeReq req = (SubscribeReq) msg;
        if ("huxing".equalsIgnoreCase(req.getUserName())) {
            System.out.println("Service accept client subscribe req: ["
                    + req.toString() + "]");
            ctx.writeAndFlush(resp(req.getSubReqID()));
        } else {
            System.out.println("Service accept client subscribe req: ["
                    + req.toString() + "]");
        }
    }

    private SubscribeResp resp(int subReqID) {
        SubscribeResp resp = new SubscribeResp();
        resp.setSubReqId(subReqID);
        resp.setRespCode(0);
        resp.setDesc("Netty boot order success, 3 days later ,sent to the designated address");
        return resp;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
